/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.value;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.entity.JEntityColumn;
import com.jianggujin.dbfly.util.JDBFlyException;

/**
 * 日期Value生成器
 *
 * @author jianggujin
 */
public class JDateValueGenerator implements JValueGenerator {

    @Override
    public Object generateValue(JEntity entity, JEntityColumn column) {
        Class<?> javaType = column.getJavaType();
        if (Date.class.equals(javaType)) {
            return new Date();
        } else if (java.sql.Timestamp.class.equals(javaType)) {
            return new java.sql.Timestamp(System.currentTimeMillis());
        } else if (java.sql.Date.class.equals(javaType)) {
            return new java.sql.Date(System.currentTimeMillis());
        } else if (java.sql.Time.class.equals(javaType)) {
            return new java.sql.Time(System.currentTimeMillis());
        } else if (String.class.equals(javaType)) {
            JFormat format = column.getField().getAnnotation(JFormat.class);
            if (format == null) {
                return DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            } else {
                return DateTimeFormatter.ofPattern(format.value());
            }
        }
        throw new JDBFlyException("@JDateValueGenerator注解不支持生成{}类型数据", javaType.getName());
    }

    /**
     * 格式化
     * 
     * @author jianggujin
     *
     */
    @Target(FIELD)
    @Retention(RUNTIME)
    public @interface JFormat {
        String value();
    }

}
